<?php

namespace App\Http\Controllers\Admin\Content;

use App\Http\Controllers\Controller;
use App\Repositories\Article\ArticleTagRepository;
use Illuminate\Http\Request;

class TagController extends Controller
{
    protected array $validateMessages = [
        'name.*' => '请输入标签名称',
        'slug.*' => '请输入标签标识',
        'color.*' => '请输入正确的标签颜色',
    ];

    public function __construct(Request $request, ArticleTagRepository $repository)
    {
        $this->request = $request;
        $this->repository = $repository;
    }


    public function index()
    {
        $list = $this->repository->paginate();
        return $this->inertia('admin/content/tag/index', [
            'data' => $list->items(),
            'pagination' => [
                'total' => $list->total(),
                'page' => $list->currentPage(),
                'pageSize' => $list->perPage(),
            ],
            'title' => '文章标签',
        ]);
    }

    public function show($id): array
    {
        return [
            'data' => $this->repository->getById($id),
        ];
    }


    public function store()
    {
        $params = $this->validate(
            $this->request,
            [
                'name' => 'required|string',
                'slug' => 'required|string',
                'color' => 'nullable|string',
            ],
            $this->validateMessages
        );
        $this->repository->create($params);
        return $this->responseCreated();
    }


    public function update($id)
    {
        $params = $this->validate(
            $this->request,
            [
                'name' => 'required|string',
                'slug' => 'required|string',
                'color' => 'nullable|string',
            ],
            $this->validateMessages
        );

        $row = $this->repository->getById($id);
        $row->update($params);
        return $this->responseSuccess();
    }

    public function destroy($id)
    {
        $row = $this->repository->getById($id);
        $row->articles()->detach();
        $row->delete();
        return $this->responseDeleted();
    }
}
